package com.view.houseon;

import java.io.OutputStream;
import java.util.ArrayList;

import com.controller.houseon.ControlHouseON;
import com.model.houseon.DEscenarioBean;
import com.presentacion.houseon.R;
import com.presentacion.houseon.R.id;
import com.presentacion.houseon.R.layout;
import com.presentacion.houseon.R.menu;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.VideoView;

public class ListaDispositivosDemoActivity extends Activity implements OnClickListener{

	
	private MjpegView mv;
	Thread	thread;
	Handler handler;
	boolean cancel;
	int cptfichier=0;
	TextView txt;
	LinearLayout linear; 
	public static  Bitmap test;	
	
   OutputStream fOut = null;

///////////////	
	
	VideoView video;
	GridView grvDispositivo;
	ArrayList<DEscenarioBean> lista;
	DEscenarioBean det;
	ToggleButton toggle;
	int idE;
	
	ImageButton ibtn_inicio;
	ImageButton ibtn_logout;
	ImageButton ibtn_filtro;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		
		//--------------------->
		  //String URL = "http://192.168.1.33:11341/cam_1.cgi"; 
		  //String URL = "http://shibuya.ipcam.jp:60001/nphMotionJpeg?Resolution=320x240&Quality=Standard";
		  String URL = "http://192.168.43.66:11341/cam_1.cgi";
		  
	        final String path = Environment.getExternalStorageDirectory().toString();
	        
	       //quitar titulo de ventana 
	        requestWindowFeature(Window.FEATURE_NO_TITLE);
	        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
	                             WindowManager.LayoutParams.FLAG_FULLSCREEN);
	        //--------------------->
	        
	        
		setContentView(R.layout.activity_lista_dispositivos_demo);
		
		Bundle b =getIntent().getExtras();
		idE=b.getInt("idEscenario");
		
		//video=(VideoView)findViewById(R.id.video_demo);	
		 //de forma alternative si queremos un streaming usar
	     //videoView.setVideoURI(Uri.parse(URLstring));
		
		//String urlpath="android.resource://"+getPackageName() +"/"+R.raw.video_demo;
		//video.setVideoPath("/mnt/sdcard/video.mp4");
		//video.setMediaController(new MediaController(this));
		//video.setVideoURI(Uri.parse("http://192.168.1.33:8080/cam_1.jpg"));
		//video.requestFocus();
		//video.start();
		
		   //--------------------->
		 mv = new MjpegView(this); 
	        
	        LinearLayout midLL = (LinearLayout)findViewById(R.id.Surface1);
	     //   LinearLayout midLL = new LinearLayout(this); 
	        midLL.findViewById(R.id.Surface1); 
	        midLL.addView(mv);
	       // midLL.addView(new MjpegView(this));
	     
	        mv.setSource(MjpegInputStream.read(URL));
	        mv.setDisplayMode(MjpegView.TAM_OK);
	        mv.showFps(true);
		
	        //--------------------->
	     
	    	ibtn_logout=(ImageButton)findViewById(R.id.ibtnInformacion);
			ibtn_logout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(ListaEscenariosActivity.this, String.valueOf("logout.."), Toast.LENGTH_SHORT).show();
				    AlertDialog.Builder alert = new AlertDialog.Builder(ListaDispositivosDemoActivity.this);
	                alert.setTitle("Desea Salir?");
	                alert.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {  
	                        salir();
	                        }});
	                           alert.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {  
	                               public void onClick(DialogInterface dialog, int whichButton) {    
	                            }});
	                       alert.show();
				}
			});
			
			ibtn_inicio=(ImageButton)findViewById(R.id.ibtnHome);
			ibtn_inicio.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(ListaEscenariosActivity.this, String.valueOf("inicio.."), Toast.LENGTH_SHORT).show();
					 Intent i = new Intent(ListaDispositivosDemoActivity.this, ListaCasaActivity.class);
					 startActivity(i);
				}
			});
			

			ibtn_filtro=(ImageButton)findViewById(R.id.ibtnEscenarios);
			ibtn_filtro.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					//Toast.makeText(ListaEscenariosActivity.this, String.valueOf("filtro.."), Toast.LENGTH_SHORT).show();
					 Intent i = new Intent(ListaDispositivosDemoActivity.this, CategoriasCasaActivity.class);
					 startActivity(i);
				}
			} );
	        
		grvDispositivo=(GridView)findViewById(R.id.grvDispositivos);
		lista= ControlHouseON.getInstancia().ListaDispositivoxEscenario(idE);
		ItemDEscenarioGridAdapter1 item= new ItemDEscenarioGridAdapter1(ListaDispositivosDemoActivity.this, lista);
		grvDispositivo.setAdapter(item);
		
		registerForContextMenu(grvDispositivo);

		grvDispositivo.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> l, View v, int position,
					long id) {
				// TODO Auto-generated method stub
				
				//Toast.makeText(ListaDispositivosActivity.this, String.valueOf("id: "+id), Toast.LENGTH_SHORT).show();
			}
		});
		
	}
	
	public void onPause() {
		super.onPause();
		mv.stopPlayback();
		
	}
	public void onCancel(DialogInterface arg0) {
		cancel=true;	
		super.onPause();
		mv.stopPlayback();
		
	}
	 public  void salir(){
	       Intent i = new Intent(); 
	                  i.setAction( Intent.ACTION_MAIN); 
	                  i.addCategory( Intent.CATEGORY_HOME); 
	                  i.setFlags( Intent.FLAG_ACTIVITY_CLEAR_TOP); 
	                  startActivity(i); 
	                  android.os.Process.killProcess( android.os.Process.myPid()); 
	                  finish();
	  }
	public static final int id_editar = 1;
	public static final int id_ver = 2;
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
	    
		menu.setHeaderTitle("Menu Opciones");  
		menu.add(0, id_editar, 0, "Editar");
		
		if(lista.get(info.position).isCamara()==true){
			//Toast.makeText(this, "estado" + lista.get(info.position).isCamara(), Toast.LENGTH_SHORT).show();
			menu.add(1, id_ver, 1, "Ver");
		}
		
	}
	
	 @Override
	    public boolean onContextItemSelected(MenuItem item) {
	        AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	        
	        det=lista.get(info.position);
	       // Toast.makeText(this, "id" + det.getIdDEscenario(), Toast.LENGTH_SHORT).show();
	        
	        switch (item.getItemId()) {

	     			case id_editar:
	        AlertDialog.Builder builder = new AlertDialog.Builder(ListaDispositivosDemoActivity.this);
		    builder.setTitle("Cuadro de Edicion");
		    builder.setView(getLayoutInflater().inflate(R.layout.dialog_personal, null))
		    // Add action buttons
		           .setPositiveButton("Guardar", new DialogInterface.OnClickListener() {
		               @Override
		               public void onClick(DialogInterface dialog, int id) {
		            	   
		            	   //e1.getIdEscenario();
		            	   Dialog diag= (Dialog)dialog;
		            	   EditText nombre_escenario= (EditText)diag.findViewById(R.id.txt_edit_nombre);
		            	   String nombre=nombre_escenario.getText().toString();
		            	   
		            	   if(ControlHouseON.getInstancia().ActualizarDetWS(det.getIdDEscenario(), nombre)){			            	   
		            		   Toast.makeText(ListaDispositivosDemoActivity.this, String.valueOf("Se actualizo"), Toast.LENGTH_SHORT).show();
		            		   Intent i= new Intent(ListaDispositivosDemoActivity.this,ListaDispositivosActivity.class);
		            		   i.putExtra("idEscenario", idE);
		            		   ListaDispositivosDemoActivity.this.finish();
		            		   startActivity(i);
		            	   }
		            	   else
		            		   Toast.makeText(ListaDispositivosDemoActivity.this, String.valueOf("Error .."), Toast.LENGTH_SHORT).show();
		               }
		           })
		           .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
		               public void onClick(DialogInterface dialog, int id) {
		                   dialog.cancel();
		               }
		           });      
		    
		    builder.show();
	        return true;
	        
	     			case id_ver:
	    				Intent i = new Intent(ListaDispositivosDemoActivity.this,VideoActivity.class);
	    				startActivity(i);
	    				return true;
	    				
	    	        }
	    	        return super.onOptionsItemSelected(item);
	    }
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.lista_dispositivos, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	
	public class ItemDEscenarioGridAdapter1 extends BaseAdapter {
		protected Activity activity;
		protected ArrayList<DEscenarioBean> items;
		ToggleButton togg;
		TextView Nombre;
		  
		public ItemDEscenarioGridAdapter1(Activity activity, ArrayList<DEscenarioBean> items) {
		    this.activity = activity;
		    this.items = items;
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return items.get(arg0).getIdDEscenario();
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View vi=convertView;
	        
		    if(convertView == null) {
		      LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		      vi = inflater.inflate(R.layout.item_dispositivos_grid, null);
		      
		      togg = (ToggleButton) vi.findViewById(R.id.tgbEncendido);
		      
		      
		      togg.setFocusable(false);
		      togg.setClickable(false); 
		      togg.setOnClickListener(checkListener);
		    }
		    
		    DEscenarioBean item = items.get(position);
		         
		    ImageView image = (ImageView) vi.findViewById(R.id.imgItemDisp);
		    int imageResource = activity.getResources().getIdentifier("drawable/"+item.getDispositivo().getImagen(), null, activity.getPackageName());
		    image.setImageDrawable(activity.getResources().getDrawable(imageResource));
		    image.setScaleType(ImageView.ScaleType.CENTER);
		    image.setPadding(20, 10,30, 10);
		    
		   	Nombre =(TextView) vi.findViewById(R.id.txtNombre_grid);
		   	Nombre.setText(item.getNombre());
		    togg.setTag(item);
		    togg.setChecked(item.isEstadoEncendido());

		    
		    return vi;
		}
		
		
		private OnClickListener checkListener = new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				DEscenarioBean d = (DEscenarioBean) v.getTag();
				d.setEstadoEncendido(!d.isEstadoEncendido());
				
				//Toast.makeText(activity, String.valueOf("id: "+d.getIdDEscenario()), Toast.LENGTH_SHORT).show();
				
				if(((ToggleButton) v).isChecked()){
					ControlHouseON.getInstancia().ActualizaEstadoD(d.getIdDEscenario());
				Toast.makeText(activity, String.valueOf("encendido"), Toast.LENGTH_SHORT).show();
				}
				else{
					ControlHouseON.getInstancia().ActualizaEstadoD(d.getIdDEscenario());
					Toast.makeText(activity, String.valueOf("apagado.."), Toast.LENGTH_SHORT).show();
				}
				
				
			}
		};

	}

}
